<template>
  <el-dialog
    title="登录"
    :custom-class="isShowProtocol ? 'custom-dialog' : 'custom-dialog is-login'"
    @closed="onClosed"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :lock-scroll="false"
    :append-to-body="true"
    top="25vh"
  >
    <template #default>
      <div class="login-protocol" v-if="isShowProtocol">
        <v-row>
          <v-col cols="12">
            <el-checkbox v-model="protocolModel[0]"
              >本人已经年满十八周岁。</el-checkbox
            >
          </v-col>

          <v-col cols="12">
            <el-checkbox v-model="protocolModel[1]">
              本人已阅读网站
              <el-button type="text" @click="handleToUserProtocol">
                <span class="text-white">用户协议</span>
              </el-button>
              ，并同意网站用户协议。
            </el-checkbox>
          </v-col>

          <v-col cols="12">
            <el-checkbox v-model="protocolModel[2]" style="width: 100%">
              <p style="white-space: initial">
                本人已知晓：ofskins的工作人员只会通过网站上注明的联系方式与我进行联系任何人假冒“ofskins工作人员”与我直接联系（特别是在Steam上）发送交易请求和其它要求的都是骗子。
              </p>
            </el-checkbox>
          </v-col>
        </v-row>

        <v-row class="justify-center mt-6">
          <v-btn
            variant="outlined"
            class="text-white"
            @click="handleClickProtocol"
            >我知道了</v-btn
          >
        </v-row>
      </div>
      <div v-else class="login-dialog">
        <p class="name">账号注册/登录</p>
        <template v-if="login.loginType == 'mobile'">
          <div class="input">
            <div
              class="el-input el-input--small el-input--prefix"
              style="height: 28px"
            >
              <input
                v-model="login.phone"
                autocomplete="off"
                class="el-input__inner"
                data-ms-editor="true"
                placeholder="请输入邮箱"
                spellcheck="false"
                type="text"
              />
              <span class="el-input__prefix">
                <i class="el-input__icon el-icon-user-solid"></i>
              </span>
            </div>
          </div>
          <div class="input">
            <div class="el-input el-input--small el-input--prefix">
              <input
                v-model="login.messageCode"
                autocomplete="off"
                class="el-input__inner"
                data-ms-editor="true"
                placeholder="请输入密码"
                spellcheck="false"
                type="text"
              />
              <span class="el-input__prefix">
                <i class="el-input__icon el-icon-s-comment"></i
              ></span>
            </div>
          </div>
        </template>
        <template v-else-if="login.loginType == 'password'">
          <div class="input">
            <div
              class="el-input el-input--small el-input--prefix"
              style="height: 28px"
            >
              <input
                v-model="login.email"
                autocomplete="off"
                class="el-input__inner"
                data-ms-editor="true"
                placeholder="请输入邮箱"
                spellcheck="false"
                type="text"
              />
              <span class="el-input__prefix">
                <i class="el-input__icon el-icon-user-solid"></i>
              </span>
            </div>
          </div>
          <div class="input">
            <div
              class="el-input el-input--small el-input--prefix"
              style="height: 28px"
            >
              <input
                v-model="login.password"
                autocomplete="off"
                class="el-input__inner"
                data-ms-editor="true"
                placeholder="请输入密码"
                spellcheck="false"
                type="password"
              />
              <span class="el-input__prefix">
                <i class="el-input__icon el-icon-lock"></i>
              </span>
            </div>
          </div>
        </template>
        <template v-else-if="login.loginType == 'email'">
          <div class="input">
            <div
              class="el-input el-input--small el-input--prefix"
              style="height: 28px"
            >
              <input
                v-model="login.email"
                autocomplete="off"
                class="el-input__inner"
                data-ms-editor="true"
                placeholder="请输入邮箱地址"
                spellcheck="false"
                type="text"
              />
              <span class="el-input__prefix">
                <i class="el-input__icon el-icon-user-solid"></i>
              </span>
            </div>
          </div>
          <div class="input">
            <div
              class="el-input el-input--small el-input--prefix"
              style="height: 28px"
            >
              <input
                v-model="login.password"
                autocomplete="off"
                class="el-input__inner"
                data-ms-editor="true"
                placeholder="请输入密码"
                spellcheck="false"
                type="password"
              />
              <span class="el-input__prefix">
                <i class="el-input__icon el-icon-lock"></i>
              </span>
            </div>
          </div>
        </template>
        <div
          class="input"
          style="margin-bottom: 0.4rem"
          v-if="login.loginType == 'mobile'"
        >
          <div class="el-input el-input--small el-input--prefix">
            <input
              v-model="login.inventCode"
              autocomplete="off"
              class="el-input__inner"
              data-ms-editor="true"
              placeholder="邀请码（可选）"
              spellcheck="false"
              type="text"
            />
            <span class="el-input__prefix">
              <i class="el-input__icon el-icon-key"></i
            ></span>
          </div>
        </div>
        <div class="change-login-type">
          <div class="login-tips">
            使用 邮箱 或者 STEAM 首次登录即可完成注册
          </div>
        </div>
        <div class="steam-login">
          <div class="steam-login-left">
            <span>其它登录方式</span>
            <img
              @click="steamLogin"
              src=""
              alt="steam登录"
            />
          </div>
          <div class="steam-login-right">
            <a href="https://uu.163.com/" target="view_window"
              >下载网易UU加速器</a
            >
          </div>
        </div>
        <div class="logindata">
          <div class="login-dialog-btn" @click="handLogin">登录</div>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { computed, reactive, ref, toRefs } from "vue";
import { useStore } from "@/store";
import { UserService } from "@/services/UserService";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";

export default {
  name: "LoginDialog",
  setup() {
    const store = useStore();
    const route = useRoute();

    const state = reactive({
      dialogVisible: false,
      login: {
        account: "",
        phone: "",
        messageCode: "",
        inventCode: getCode(),
        loginType: "password",
        email:'',
        password: "",
        ticket: "",
        rand_str: "",
      },
      store: computed(() => store),
      recharge: false,
      buttonText: "获取验证码",
      n: 60,
      loading: false,
      showPhoneCodeSec:false,
      codeImg:'',
      sCode:null
    });

    async function handLogin() {
      if(state.login.loginType=='mobile'){
        if (state.login.phone.length == 0) {
          ElMessage.error("请输入登录手机号");
          return;
        }
      } else if (state.login.loginType == "mobile") {
        if (state.login.messageCode.length == 0) {
          ElMessage.error("请输入短信验证码");
          return;
        }
      } else if (state.login.loginType == "password") {
        if (state.login.password.length == 0) {
          ElMessage.error("请输入密码");
          return;
        }
      } else if(state.login.loginType == 'email'){
        if (state.login.email.length == 0 || state.login.email.indexOf('@')===-1) {
          ElMessage.error("请输入正确的邮箱地址");
          return;
        }
        if(state.login.password.length == 0){
          ElMessage.error("请输入密码");
          return;
        }
      }

      return UserService.login({
        login_type: state.login.loginType,
        mobile: state.login.phone,
        email:state.login.email,
        code: state.login.messageCode,
        invite_code: state.login.inventCode,
        password: state.login.password,
        ticket: state.login.ticket,
        rand_str: state.login.rand_str,
      }).then((login) => {
        if (login.data.data.access_token) {
          const token = login.data.data.access_token;
          UserService.setToken(token);
          commitUserToken(token);
        }
      });
    }

    function commitUserToken(token) {
      store.commit("setToken", token);
      window.location.reload();
    }

    function changeLoginType(type) {
      state.login.loginType = type;
    }
    function getCode() {
      const searchParams = new URLSearchParams(window.location.search);
      let code = ''
      if (searchParams.has("code")) {
        code = searchParams.get("code");
      }
      return code
    }
    function steamLogin() {
      const steamAuthUrl = `${
        import.meta.env.VITE_BASE_URL
      }/api/user/auth/steam`;
      window.open(
        steamAuthUrl,
        "_blank",
        "width=900,height=600,menubar=no,toolbar=no, status=no,scrollbars=yes"
      );
    }

    return {
      ...toRefs(state),
      handLogin,
      changeLoginType,
      steamLogin,
      protocolModel: ref([1, 1, 1].map(() => true)),
      isShowProtocol: ref(true),
      router: useRouter()
    };
  },

  methods: {
    handleClickProtocol() {
      for (let i = 0; i < this.protocolModel.length; i++) {
        if (!this.protocolModel[i]) {
          this.$notify.warning("请先阅读以下协议并勾选同意");
          return;
        }
      }

      this.isShowProtocol = false;
    },

    onClosed() {
      this.isShowProtocol = true;
      this.protocolModel = this.protocolModel.map(() => true);
      this.login.phone = "";
      this.login.messageCode = "";
      this.login.inventCode = "";
      this.login.loginType = "mobile";
      this.login.password = "";
    },

    handleToUserProtocol() {
      this.router.push("/service");
      this.$emit("close");
    },
  },
};
</script>
<style lang="scss">
.el-dialog {
  background: #1a1d2d;

  @media screen and (max-width: 768px) {
    width: 100% !important;
  }

  .el-dialog__header {
    background-color: #232036;
    padding: 10px 20px;

    .el-dialog__title {
      color: #5d5c66;
    }
    .el-dialog__headerbtn {
      top: 10px;
      right: 10px;
      font-size: 20px;
    }
  }

  .el-dialog__body {
    background: #1a1d2d;
  }
}

.is-login {
  max-width: 400px;
}

.login-dialog {
  .name {
    text-align: center;
    height: 1.75rem;
    font-size: 1.5rem;
    font-weight: 800;
    color: #fff;
    line-height: 1.75rem;
    margin: 0 auto;
    padding: 0 auto;
  }

  .input {
    width: 100%;
    padding: 0 2rem;
    position: relative;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    margin-bottom: 1.4rem;

    .validation {
      height: 100%;
      font-size: 0.75rem;
      font-weight: 400;
      color: #ff6138;
      right: 2.5rem;
      transform: scale(0.9);
      position: absolute;
      cursor: pointer;
      background-color: transparent;
      border-style: none;
    }
  }

  .steam-login {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    -ms-flex-line-pack: center;
    align-content: center;
    padding: 0 2rem;

    .steam-login-left {
      display: -webkit-box;
      display: -ms-flexbox;
      display: flex;
      -webkit-box-align: center;
      -ms-flex-align: center;
      align-items: center;

      span {
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #666;
        line-height: 17px;
        margin-right: 10px;
      }
      img {
        width: 32px;
        height: 32px;
        cursor: pointer;
      }
    }

    .steam-login-right {
      cursor: pointer;
      display: -webkit-box;
      display: -ms-flexbox;
      display: flex;
      -webkit-box-pack: end;
      -ms-flex-pack: end;
      justify-content: flex-end;
      -webkit-box-align: center;
      -ms-flex-align: center;
      align-items: center;
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #f8f8f8;
      line-height: 17px;
      a,
      a:active,
      a:focus,
      a:hover,
      a:link,
      a:visited {
        color: inherit;
        padding: 0;
        margin: 0;
        -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
        -webkit-tap-highlight-color: transparent;
        outline: none;
        background: none;
        text-decoration: none;
      }
    }
  }

  .logindata {
    margin: 2.2rem 0;
    text-align: center;

    & .login-dialog-btn {
      line-height: 3.3rem;
      width: 13rem;
      height: 3rem;
      font-size: 1rem;
      font-weight: 500;
      color: #fff;
      margin: 0 auto;
      cursor: pointer;
      background: #8e7eed;
      border-radius: 4px;
    }
  }
}

.input {
  margin: 20px 0;
}

.change-login-type {
  padding: 0 2rem;
  position: relative;
  display: flex;
  flex-direction: column;
  margin-bottom: 1.4rem;
  color: #c2b9f1;
  .login-type {
    cursor: pointer;
  }
  .login-tips {
    font-size: 12px;
  }
}
  .codeBtn{
    white-space: nowrap;
    height: 32px;
    background:#8e7eed;
    width: 250px;
    line-height: 30px;
    text-align: center;
    margin-left: 10px;
    border-radius: 4px;
    color: #ffffff;
    cursor: pointer;
    font-size: 8px;
  }
  .codeImg{
    background-color: #ffffff;
    width: 300px;
    height: 30px;
    border-radius: 4px;
    margin-right: 10px;
    .cimg{
      width: 100%;
      height: 100%;
      object-fit: cover;
      cursor: pointer;
    }
  }
</style>
